package com.example.file_management.controller;

import com.example.file_management.pojo.user.Auth;
import com.example.file_management.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpHeaders;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "http://localhost:5173")
public class AuthController {

    @Autowired
    private AuthService authService;

    // 用户登录
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");

        try {
            return ResponseEntity.ok(authService.login(username, password));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 获取所有用户
    @GetMapping("/users")
    public ResponseEntity<List<Auth>> getAllUsers() {
        return ResponseEntity.ok(authService.getAllUsers());
    }

    // 根据 groupId 获取用户
    @GetMapping("/users/group/{groupId}")
    public ResponseEntity<List<Auth>> getUsersByGroupId(@PathVariable Long groupId) {
        return ResponseEntity.ok(authService.getUsersByGroupId(groupId));
    }

    @GetMapping("/current-user")
    public ResponseEntity<Auth> getCurrentUser(@RequestHeader("Authorization") String token) {
        // 清理Token中的空白字符
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7).trim(); // 去掉 "Bearer " 前缀并清理空格
        } else {
            return ResponseEntity.badRequest().body(null); // 如果 Token 格式不对，直接返回 400
        }

        try {
            Auth user = authService.getCurrentUser(token);
            return ResponseEntity.ok(user);
        } catch (IllegalArgumentException e) {
            // 返回空的Auth对象，并设置状态码为400
            return ResponseEntity.badRequest().body(null);
        } catch (io.jsonwebtoken.io.DecodingException | io.jsonwebtoken.MalformedJwtException e) {
            // 创建一个包含错误信息的Auth对象
            Auth errorAuth = new Auth();
            errorAuth.setError("无效的JWT Token"); // 使用 setter 方法设置 error 字段
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Error", "Invalid JWT Token");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .headers(httpHeaders)
                    .body(errorAuth);
        } catch (Exception e) {
            // 记录其他异常
            System.err.println("获取当前用户时发生未知错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    // 根据 roleId 获取用户
    @GetMapping("/users/role/{roleId}")
    public ResponseEntity<List<Auth>> getUsersByRoleId(@PathVariable Long roleId) {
        return ResponseEntity.ok(authService.getUsersByRoleId(roleId));
    }
    @GetMapping("/getUserByUsername")
    public Auth getUserByUsername(@RequestParam String username) {
        return authService.getUserByUsername(username);
    }
    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@RequestBody Auth user) {
        try {
            // 修改为通过依赖注入的实例调用
            String result = authService.registerUser(user);
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("注册失败: 系统错误，请稍后再试");
        }
    }

    // 注销用户
    @DeleteMapping("/user/{userId}")
    public ResponseEntity<String> deleteUser(@PathVariable Long userId) {
        String result = authService.deleteUser(userId);
        if (result.contains("成功")) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    // 更新用户信息
    @PutMapping("/user")
    public ResponseEntity<String> updateUser(@RequestBody Auth user) {
        try {
            return ResponseEntity.ok(authService.updateUser(user));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}
